<template>
  <div>
    <div class="flex-row bg-primary pb-3">
      <div class="ml-3">
        <text class="panel-hint">{{year}}年</text>
        <div class="flex-row panel-month"
             @click="handleMonthPick">
          <text class="panel-date-month">{{fullMonth}}</text>
          <text class="month-text">月</text>
          <text class="icon month-icon">&#xe604;</text>
        </div>
      </div>
      <div class="flex ml-3"
           @click="goList(1)">
        <text class="panel-num-hint">收入</text>
        <div class="flex-row align-items-end">
          <text class="panel-number-int">{{totalMonthFunds.inArr[0]}}</text>
          <text class="panel-number-dec">.{{totalMonthFunds.inArr[1]}}</text>
        </div>
      </div>
      <div class="flex ml-3"
           @click="goList(2)">
        <text class="panel-num-hint">支出</text>
        <div class="flex-row align-items-end">
          <text class="panel-number-int">{{totalMonthFunds.outArr[0]}}</text>
          <text class="panel-number-dec">.{{totalMonthFunds.outArr[1]}}</text>
        </div>
      </div>
      <div class="flex ml-3">
        <text class="panel-num-hint">结余</text>
        <div class="flex-row align-items-end">
          <text class="panel-number-int">{{totalMonthFunds.remainArr[0]}}</text>
          <text class="panel-number-dec">.{{totalMonthFunds.remainArr[1]}}</text>
        </div>
      </div>
    </div>

    <scroller :show-scrollbar="false"
              class="scroller bg-white">
      <!-- <refresh class="a-refresh"
               :display="refreshing ? 'show' : 'hide'"
               @refresh="refresh"
               @pullingdown="onpullingdown">
        <text class="scroller-text">{{refreshText}}</text>
      </refresh> -->

      <vm-status v-if="showStatus"
                 :empty-text="`${year}年${month}月 暂无数据`"
                 :hint-text="isError ? '' : '快去记一笔吧'"
                 :type="isError ? 'error' : 'empty'"></vm-status>

      <div v-for="(item, index) in list"
           :key="index">
        <div class="account-item">
          <text class="account-date">{{item.dateStr}}</text>
          <div class="flex-row">
            <text class="account-date">{{item.calcIn?`收入: ${item.calcIn}`:''}}</text>
            <text class="account-date ml-5">{{item.calcOut?`支出: ${item.calcOut}`:''}}</text>
          </div>
        </div>
        <div v-for="(record, serial) in item.records"
             :key="serial"
             class="flex-row"
             @click="goDetail(record)">
          <image class="account-icon"
                 :src="record.icon"></image>
          <div class="account-main"
               :class="[record.isLast&&'account-main-last']">
            <text class="account-remark"
                  :class="[record.isIn?'text-success':'text-error']">{{record.remarkStr}}</text>
            <text class="account-number"
                  :class="[record.isIn?'text-success':'text-error']">{{record.account_funds}}</text>
          </div>
        </div>
      </div>

      <!-- <loading :display="loading ? 'show' : 'hide'"
               @loading="loadmore"
               @pullingup="onpullingup">
        <text class="scroller-text">{{loadingText}}</text>
      </loading> -->
    </scroller>

    <div class="btn-add"
         @click="goEdit">
      <text class="icon btn-text">&#xe69f;</text>
    </div>
  </div>
</template>
<script>
import VmStatus from '../../components/vm-status.vue'
import {
  STORAGE_USER,
  STORAGE_FARM,
  EVENT_GET_FARM,
  EVENT_GET_USER,
  EVENT_GET_ACCOUNT_RECORD
} from '../../plugins/constant'
import { calcNumber, fillByChar, getDaysInMonth } from '../../plugins/utils'
import { convert } from './convert'

const globalEvent = weex.requireModule('globalEvent')

export default {
  components: {
    VmStatus
  },
  props: {},
  data() {
    return {
      homeBackClickTime: +new Date(),

      farm: {},
      params: {
        'farm_id.eq': '',
        'account_date.gte': '',
        'account_date.lte': ''
      },
      isError: false,
      list: [],

      // 自定义上下拉逻辑
      refreshing: false,
      refreshText: '下拉查看下月数据',
      loading: false,
      loadingText: '上拉查看上月数据',

      // 时间
      year: '',
      month: ''
    }
  },
  computed: {
    showStatus() {
      return this.isError || !this.list.length
    },
    fullMonth() {
      return fillByChar(this.month)
    },
    // 统计金额计算、把整数与小数部分分开（有两位小数点）
    totalMonthFunds() {
      let totalIn = 0
      let totalOut = 0
      for (const item of this.list) {
        totalIn += item.calcIn
        totalOut += item.calcOut
      }
      totalIn = calcNumber(totalIn)
      totalOut = calcNumber(totalOut)
      let totalRemain = calcNumber(totalIn - totalOut)
      return {
        in: totalIn,
        out: totalOut,
        remain: totalRemain,
        inArr: this.splitNumber(totalIn),
        outArr: this.splitNumber(totalOut),
        remainArr: this.splitNumber(totalRemain)
      }
    },
    startAndEndDate() {
      const dateStr = `${this.year}-${this.fullMonth}`
      const monthDays = getDaysInMonth(this.year, this.month)
      return {
        start: `${dateStr}-01`,
        end: `${dateStr}-${monthDays} 23:59:59`
      }
    }
  },
  watch: {},
  eros: {
    beforeBackAppear(params) {
      if (!params) { return }
      if (params.type === 1) {
        this.getData()
      }
    }
  },
  created() {
    // 初始化日期
    const currentDate = new Date()
    this.year = currentDate.getFullYear()
    this.month = currentDate.getMonth() + 1

    // tab页，要监听农场获取事件
    this.$event.on(EVENT_GET_FARM, res => {
      if (res.id !== this.farm.id) {
        this.farm = res
        this.initData()
      }
    })
    this.$event.on(EVENT_GET_USER, res => {
      this.user = res
    })

    // 监听三级页面修改事件
    this.$event.on(EVENT_GET_ACCOUNT_RECORD, res => {
      this.getData()
    })

    this.getFarm()
    this.androidFinishApp()
  },
  mounted() { },
  methods: {
    androidFinishApp() {
      globalEvent.addEventListener('homeBack', options => {
        const timeNow = new Date().getTime()
        if (timeNow - this.homeBackClickTime > 2000) {
          this.$notice.toast({ message: '再按一次退出应用' })
          this.homeBackClickTime = timeNow
        } else {
          this.$router.finish()
        }
      })
    },
    getFarm() {
      this.user = this.$storage.getSync(STORAGE_USER) || {}
      this.farm = this.$storage.getSync(STORAGE_FARM) || {}
      if (this.farm.id) {
        this.initData()
      }
    },
    // 下载加载下月数据
    refresh(e) {
      this.refreshing = true
      this.refreshText = '加载中...'
      this.addMonth()
      this.getData().catch(() => {
        this.minusMonth()
      }).finally(() => {
        this.refreshText = '加载完成'
        this.refreshing = false
      })
    },
    loadmore(e) {
      this.loading = true
      this.loadingText = '加载中...'
      this.minusMonth()
      this.getData().catch(() => {
        this.addMonth()
      }).finally(() => {
        this.loadingText = '加载完成'
        this.loading = false
      })
    },
    addMonth() {
      if (this.month > 11) {
        this.month = 1
        this.year++
      } else {
        this.month++
      }
    },
    minusMonth() {
      if (this.month < 2) {
        this.month = 12
        this.year--
      } else {
        this.month--
      }
    },
    onpullingdown({ pullingDistance, viewHeight }) {
      this.refreshText = `${pullingDistance >= viewHeight ? '松开' : '下拉'}查看下月数据`
    },
    onpullingup({ pullingDistance, viewHeight }) {
      console.log(pullingDistance)
      this.loadingText = `${pullingDistance >= viewHeight ? '松开' : '上拉'}查看上月数据`
    },
    // 分隔数字
    splitNumber(number) {
      const arr = `${number}`.split('.')
      const intNum = arr[0] || '0'
      let decNum = arr[1] || '00'
      if (decNum.length < 2) {
        decNum += '0'
      }
      return [intNum, decNum]
    },
    // 获取数据
    initData() {
      this.params['farm_id.eq'] = this.farm.id
      this.getData()
    },
    getData() {
      if (this.isError) {
        return this.$notice.toast({ message: '获取数据失败' })
      }

      this.params['account_date.gte'] = this.startAndEndDate.start
      this.params['account_date.lte'] = this.startAndEndDate.end

      return this.$api.getData({
        server: 'agr_chain',
        table: 'account_record_app_view',
        params: this.params,
        order: {
          account_date: 'desc'
        },
        errorMsg: '获取记账数据失败'
      }).then(res => {
        const data = res || []

        // 按天统计金额
        const resData = [] // 两层列表，第一层以天为维度的统计，第二层是当天的记账列表
        for (let i = 0; i < data.length; i++) {
          const item = convert(data[i])

          item.isLast = true
          item.editEnable = item.submit_person === this.user.userId

          const itemInAndOut = this.getInAndOutFunds(item.account_funds, item.isIn)
          const lastData = resData[resData.length - 1]
          if (i === 0 || item.dateStr !== lastData.dateStr) {
            resData.push({
              dateStr: item.dateStr,
              calcIn: itemInAndOut[0],
              calcOut: itemInAndOut[1],
              records: [item]
            })
          } else {
            lastData.calcIn = calcNumber(lastData.calcIn + itemInAndOut[0])
            lastData.calcOut = calcNumber(lastData.calcOut + itemInAndOut[1])
            lastData.records[lastData.records.length - 1].isLast = false
            lastData.records.push(item)
          }
        }

        this.list = resData
      })
    },
    // 根据 account_record_type 计算当前的收入支出：1 收入 2 支出
    getInAndOutFunds(accountFunds, isIn) {
      let inNum = 0
      let outNum = 0
      let funds = Number.parseFloat(accountFunds)
      if (isNaN(funds)) {
        funds = 0
      }
      if (isIn) {
        inNum = funds
      } else {
        outNum = funds
      }
      return [inNum, outNum]
    },

    // 月份选择
    handleMonthPick() {
      this.$dialog.datePick({
        initialDate: `${this.year}-${this.fullMonth}-01`,
        type: 1,
        onPositive: res => {
          this.year = Number.parseInt(res.year, 10)
          this.month = Number.parseInt(res.month, 10)
          this.getData()
        }
      })
    },

    goEdit() {
      this.$nav.open({
        name: 'account.record.edit',
        type: 2,
        params: {}
      })
    },
    goDetail(record) {
      this.$nav.open({
        name: 'account.record.detail',
        params: { record }
      })
    },
    goList(type = 1) {
      this.$nav.open({
        name: 'account.record.list',
        params: {
          type,
          startDate: this.startAndEndDate.start,
          endDate: this.startAndEndDate.end
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import "../../css/variables.scss";
$panel-bg: $primary;
$panel-color: #fff;

.icon {
  font-family: alicon;
}
.flex-row {
  flex-direction: row;
}
.flex {
  flex: 1;
}
.justify-content-end {
  justify-content: flex-end;
}
.align-items-end {
  align-items: flex-end;
}
.align-items-center {
  align-items: center;
}

.p-3 {
  padding: 15px;
}
.px-3 {
  padding-left: 15px;
  padding-right: 15px;
}
.pr-3 {
  padding-right: 15px;
}
.pb-3 {
  padding-bottom: 15px;
}
.ml-3 {
  margin-left: 15px;
}
.ml-5 {
  margin-left: 25px;
}
.bg-primary {
  background-color: $primary;
}
.bg-white {
  background-color: #fff;
}
.text-success {
  color: $success;
}
.text-error {
  color: $error;
}

.a-refresh {
  position: absolute;
  width: 750;
  align-items: center;
  justify-content: flex-end;
}
.scroller-text {
  font-size: 26px;
  padding: 50px;
  text-align: center;
  color: $gray-600;
}

.panel-month {
  align-items: center;
  border-right-width: 1px;
  border-right-color: rgba(255, 255, 255, 0.8);
  border-right-style: solid;
  padding-right: 25px;
}
.panel-hint {
  font-size: 24px;
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 10px;
  font-weight: 400;
}
.panel-date-month {
  font-size: 42px;
  color: $panel-color;
  margin-right: 5px;
}
.month-text {
  color: $panel-color;
  font-size: 26px;
  margin-right: 15px;
}
.month-icon {
  color: $panel-color;
  font-size: 24px;
}
.panel-num-hint {
  font-size: 24px;
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 20px;
  font-weight: 400;
}
.panel-number-int {
  color: $panel-color;
  font-size: 34px;
}
.panel-number-dec {
  color: $panel-color;
  font-size: 22px;
  padding-bottom: 2px;
}

.btn-add {
  position: absolute;
  right: 50px;
  bottom: 30px;
  width: 100px;
  height: 100px;
  padding: 0;
  background-color: $accent;
  border-radius: 50px;
  text-align: center;
  box-shadow: 3px 2px 5px rgba(128, 128, 128, 0.5);
  align-items: center;
  justify-content: center;
}
.btn-text {
  text-align: center;
  color: #fff;
  font-size: 60px;
  font-weight: bold;
}
.btn-add:active {
  background-color: #cca410;
}

.account-icon {
  width: 40px;
  height: 40px;
  margin: 30px;
}
.account-main {
  flex-direction: row;
  flex: 1;
  padding-top: 30px;
  padding-right: 30px;
  padding-bottom: 30;
  border-bottom-width: 1px;
  border-bottom-color: $border-color-light;
  border-bottom-style: solid;
}
.account-main-last {
  border-bottom-width: 0;
}
.account-remark {
  flex: 1;
  font-size: 28px;
  padding-right: 30px;
}
.account-number {
  font-size: 28px;
  min-width: 200px;
}
.account-item {
  flex-direction: row;
  justify-content: space-between;
  padding-top: 20px;
  padding-left: 15px;
  padding-right: 15px;
  padding-bottom: 15px;
  border-bottom-width: 1px;
  border-bottom-color: $border-color;
  border-bottom-style: solid;
}
.account-date {
  font-size: 24px;
  color: $gray-500;
}
</style>
